package binaryOctopus;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

/**
 * The CheckersGui is the driver that that runs the gui of the game
 * and creates the game and calls the methods so that game and gui,
 * can interacte with each other.  
 */
public class CheckersGui implements ActionListener
{               
	//start menu vars
	private JFrame startFrame;

	//game frame vars
	private JFrame frame;
	private JPanel contentPane;
	
	private JFrame popFra;
	
	private boolean newFromMenuBar = true;

	private boolean playAI = false;
	//private boolean playHuman = false;
	private boolean gameOver = false;

	private JPanel panel;
	private JPanel timer;
			
	private JTextField txtTurn;

	private long elapsedTimeSec;
	private boolean gameLoaded = false;
	
	//sets size of the board
	private Dimension boardSize = new Dimension(600, 600);
	//declares the number of rows and columns on board      
	private final int numRows = 8;
	private final int numCols = 8;
	
	//private Game game; // = new Game(numRows, numCols);

	//sets the piece that was clicked
	//private int squaresClicked = 0;
	//private ClickableImage pieceSelected;

	//declare a board
	Board board = null;
	//creates a border to highlight a piece when selected   
	Border clickedPiece = BorderFactory.createLineBorder(Color.MAGENTA, 3);

	//declare stats to be kept
	Stats stats = new Stats("stats.txt");
	/**
	 * main method to initialize gui
	 */
	public static void main(String[] args) 
	{
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					
					CheckersGui gui = new CheckersGui();


				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	// Constructor creates all GUI components
	public CheckersGui( ) 
	{
			//start menu
			setUpStartMenu();
		
			//board gui will be displayed only when the start or load
			//option is selected from the main start menu
			//hence - code for this is called in the newGame() and loadGame() funct's
	}
	
	
	private void setUpStartMenu()
	{
		startFrame = new JFrame("CHECKERS");
		startFrame.setAlwaysOnTop(true);
		startFrame.requestFocusInWindow();
		//startFrame.setSize(210, 440);
		startFrame.setBounds(500, 50, 210, 440);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{252};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		startFrame.getContentPane().setBackground(Color.PINK);
		startFrame.getContentPane().setLayout(gridBagLayout);


		JLabel lblCheckers = new JLabel("CHECKERS!");
		GridBagConstraints gbc_lblCheckers = new GridBagConstraints();
		gbc_lblCheckers.insets = new Insets(0, 0, 5, 0);
		gbc_lblCheckers.gridx = 0;
		gbc_lblCheckers.gridy = 0;
		startFrame.getContentPane().add(lblCheckers, gbc_lblCheckers);

		JButton btnNewGame = new JButton("New Game");
		GridBagConstraints gbc_btnNewGame = new GridBagConstraints();
		gbc_btnNewGame.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewGame.gridx = 0;
		gbc_btnNewGame.gridy = 2;

		//When starting a new game - pop up whether player wants human vs human/AI
		btnNewGame.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//new button -> human/ai window -> gui 
				startFrame.dispose();
				newMenu();
			}
		});   


		startFrame.getContentPane().add(btnNewGame, gbc_btnNewGame);

		JButton btnLoadGame = new JButton("Load Game");
		GridBagConstraints gbc_btnLoadGame = new GridBagConstraints();
		gbc_btnLoadGame.insets = new Insets(0, 0, 5, 0);
		gbc_btnLoadGame.gridx = 0;
		gbc_btnLoadGame.gridy = 3;

		//code to execute when user wants to load a previous game
		btnLoadGame.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//IF NO GAME HAS BEEN LOADED - pop up error message
				if(!savedGameExists())
				{
					int result2 = JOptionPane.showConfirmDialog(startFrame,
							"Error!\n" +
							"No games have been previously saved.\n" +
							"Would you like to play a new game?",
							"Load Game Error",
							JOptionPane.OK_CANCEL_OPTION,
							JOptionPane.WARNING_MESSAGE);
	
					if (result2 == JOptionPane.OK_OPTION)
					{
						startFrame.dispose();
						newMenu();
					}
					else if (result2 == JOptionPane.CANCEL_OPTION)
					{
						//do nothing - just return to start menu
					}
				}
				else
				{
					//else if a game has been saved
					loadGame(true);
				}
			}
		});

		startFrame.getContentPane().add(btnLoadGame, gbc_btnLoadGame);

		JButton btnStatistics = new JButton("Statistics");
		GridBagConstraints gbc_btnStatistics = new GridBagConstraints();
		gbc_btnStatistics.insets = new Insets(0, 0, 5, 0);
		gbc_btnStatistics.gridx = 0;
		gbc_btnStatistics.gridy = 4;

		//Display the statistics From the start menu
		btnStatistics.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				stats();
			}
		});

		startFrame.getContentPane().add(btnStatistics, gbc_btnStatistics);

		JButton btnHelp = new JButton("Help");
		GridBagConstraints gbc_btnHelp = new GridBagConstraints();
		gbc_btnHelp.insets = new Insets(0, 0, 5, 0);
		gbc_btnHelp.gridx = 0;
		gbc_btnHelp.gridy = 5;
		startFrame.getContentPane().add(btnHelp, gbc_btnHelp);

		btnHelp.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				helpMenu();
			}
		});

		JButton btnExit = new JButton("Exit");
		GridBagConstraints gbc_btnExit = new GridBagConstraints();
		gbc_btnExit.insets = new Insets(0, 0, 5, 0);
		gbc_btnExit.gridx = 0;
		gbc_btnExit.gridy = 6;

		btnExit.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				System.exit(0);
			}
		});

		startFrame.getContentPane().add(btnExit, gbc_btnExit);
		startFrame.setVisible(true);


		JPanel panelIMG = new ImagePanel();
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 8;
		startFrame.getContentPane().add(panelIMG, gbc_panel);
	}

	private void newMenu()
	{
		popFra = new JFrame("CHECKERS");
		//popFra.setSize(260, 178);
		popFra.setBounds(500, 200, 260, 178);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{260};
		gridBagLayout.rowHeights = new int[]{70, 49, 53, 10};
		gridBagLayout.columnWeights = new double[]{0.0};
		gridBagLayout.rowWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE};
		popFra.getContentPane().setLayout(gridBagLayout);
		popFra.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

		JLabel lblSelectAGame = new JLabel("Select A Game Mode");
		lblSelectAGame.setHorizontalAlignment(SwingConstants.CENTER);
		lblSelectAGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
		GridBagConstraints gbc_lblSelectAGame = new GridBagConstraints();
		gbc_lblSelectAGame.anchor = GridBagConstraints.NORTH;
		gbc_lblSelectAGame.fill = GridBagConstraints.HORIZONTAL;
		gbc_lblSelectAGame.insets = new Insets(0, 0, 5, 0);
		gbc_lblSelectAGame.gridx = 0;
		gbc_lblSelectAGame.gridy = 0;
		popFra.getContentPane().add(lblSelectAGame, gbc_lblSelectAGame);

		JButton btnHumanVsAi = new JButton("HUMAN vs. AI");
		btnHumanVsAi.setForeground(new Color(255, 20, 147));
		GridBagConstraints gbc_btnHumanVsAi = new GridBagConstraints();
		gbc_btnHumanVsAi.insets = new Insets(0, 0, 5, 0);
		gbc_btnHumanVsAi.gridx = 0;
		gbc_btnHumanVsAi.gridy = 1;

		//when player want human v AI
		btnHumanVsAi.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				playAI = true;
				popFra.dispose();
				
				
				//if this is the first time we are playing a game
				//set up the whole board gui, else
				//we're going to use current board
				if(newFromMenuBar)
				{
					setUpGameGUI();
				}
					
				newGame();
			}
		});

		popFra.getContentPane().add(btnHumanVsAi, gbc_btnHumanVsAi);

		JButton btnHumanVsHuman = new JButton("HUMAN vs. HUMAN");
		btnHumanVsHuman.setForeground(new Color(255, 20, 147));
		GridBagConstraints gbc_btnHumanVsHuman = new GridBagConstraints();
		gbc_btnHumanVsHuman.gridx = 0;
		gbc_btnHumanVsHuman.gridy = 2;

		//when player wants human v human
		btnHumanVsHuman.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				playAI = false;
				popFra.dispose();
				
				
				//if this is the first time we are playing a game
				//set up the whole board gui, else
				//we're going to use current board
				if(newFromMenuBar)
				{
					setUpGameGUI();
				}
				
				newGame();
			}
		});

		popFra.getContentPane().add(btnHumanVsHuman, gbc_btnHumanVsHuman);

		popFra.setVisible(true);
	}

	private void setUpGameGUI() 
	{
		//initialize checkersGUI frame
		frame = new JFrame("CHECKERS");
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		//confirm exit button to allow for saving of board configuration
		frame.addWindowListener( new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				//customized exiting
				exit();
			}
		});

		//Display the window.
		frame.setBounds(300, 50, 550, 645);
		frame.setVisible(true);

		//set up content pane -> holds all items within the frame
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		frame.setContentPane(contentPane);
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

		//Create and set up menu
		setUpMenuBar();

		//game layout type
		SpringLayout sl_contentPane = new SpringLayout();
		contentPane.setLayout(sl_contentPane);

		//text field to display who's turn it is       
		txtTurn = new JTextField();
		txtTurn.setEditable(false);
		sl_contentPane.putConstraint(SpringLayout.NORTH, txtTurn, 19, SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, txtTurn, 140, SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.SOUTH, txtTurn, 49, SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, txtTurn, 411, SpringLayout.WEST, contentPane);
		txtTurn.setHorizontalAlignment(SwingConstants.CENTER);
		txtTurn.setBounds(10, 88, 100, 28);
		contentPane.add(txtTurn);
		txtTurn.setColumns(5);
		txtTurn.setText("Player 1's Turn (Black)");

		//panel to contain board
		panel = new JPanel();
		panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		sl_contentPane.putConstraint(SpringLayout.NORTH, panel, 10, SpringLayout.SOUTH, txtTurn);
		sl_contentPane.putConstraint(SpringLayout.WEST, panel, 10, SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.SOUTH, panel, -10, SpringLayout.SOUTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, panel, -10, SpringLayout.EAST, contentPane);
		contentPane.add(panel);
		
			
		// create the panel that holds the buttons
		//this section can most likely be deleted but saved for reference
		//              JPanel jpButtons = new JPanel( );
		//              jpButtons.setLayout( new GridLayout(1, 5));
		//              Border btnBorder = BorderFactory.createRaisedBevelBorder();
		//              Dimension btnDimension = new Dimension(50, 50);
		//              Font btnFont = new Font("Times New Roman", Font.BOLD, 24);
	}
	
	
	private void newBoard()
	{
		// Timer
		setTimer(0);
		
		panel.removeAll();
		txtTurn.setText("Player 1's Turn (Black)");
		
		ImageIcon blackPiece = new ImageIcon("blackPiece.gif");
		ImageIcon redPiece = new ImageIcon("redPiece.gif");
		
		//creates a new board
		board = new Board(numRows, numCols,this);

		for(int i=0; i<3; i++)
		{
			for(int j=0; j<8; j++)
			{
				if(board.getButton(i, j).getBackground().equals(Color.BLACK))
				{
					board.placePiece(blackPiece, i, j);
					//Coordinates pieceB = new Coordinates(i, j);
				}
			}
		}

		for(int i=5; i<8; i++)
		{
			for(int j=0; j<8; j++)
			{
				if(board.getButton(i, j).getBackground().equals(Color.BLACK))
				{
					board.placePiece(redPiece, i, j);
				}
			}
		}
		
		//adds board to the panel
		panel.add(board);
	}
	
	
	//action items for menu bar 
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//Handle Actions Corresponding to Menu Items    
		JMenuItem source = (JMenuItem)(e.getSource());


		if(source.getText().equals("New Game"))
		{
			//if no game is currently being played
			if(gameOver == true)
			{
				newMenu();
			}
			//else if user tries to play new game
			// while in the middle of a game already
			else
			{
				int result = JOptionPane.showConfirmDialog(frame,
						"This will end your current game!\n" +
						"Would you like to surrender this game\n" +
						"then start a new one?\n",
						"WARNING!",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);

				if (result == JOptionPane.YES_OPTION)
				{
					surrender();
					
					newMenu();
				}
				else if (result == JOptionPane.NO_OPTION)
				{
					// do nothing - let user continue playing game
				}
			}
		}
		else if(source.getText().equals("Load Game"))
		{			
			
			//if no game is currently being played
			if(gameOver == true)
			{
				//IF NO GAME HAS BEEN LOADED - pop up error message
				if(!savedGameExists())
				{
					int result2 = JOptionPane.showConfirmDialog(startFrame,
							"Error!\n" +
							"No games have been previously saved.\n" +
							"Would you like to play a new game?",
							"Load Game Error",
							JOptionPane.OK_CANCEL_OPTION,
							JOptionPane.WARNING_MESSAGE);
	
					if (result2 == JOptionPane.OK_OPTION)
					{
						//NEW GAME
						newMenu();
					}
					else if (result2 == JOptionPane.CANCEL_OPTION)
					{
						//do nothing - return to gui
					}
				}
				else
					loadGame(true);
			}
			//else if user tries to play new game
			// while in the middle of a game already
			else
			{
				int result = JOptionPane.showConfirmDialog(frame,
						"This will end your current game!\n" +
						"Would you like to surrender this game\n" +
						"then load the most recently saved game?\n",
						"WARNING!",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);

				if (result == JOptionPane.YES_OPTION)
				{					
					//IF NO GAME HAS BEEN LOADED - pop up error message
					if(!savedGameExists())
					{
						int result2 = JOptionPane.showConfirmDialog(startFrame,
								"Error!\n" +
								"No games have been previously saved.\n" +
								"Would you like to play a new game?",
								"Load Game Error",
								JOptionPane.OK_CANCEL_OPTION,
								JOptionPane.WARNING_MESSAGE);
		
						if (result2 == JOptionPane.OK_OPTION)
						{
							//NEW GAME
							newMenu();
						}
						else if (result2 == JOptionPane.CANCEL_OPTION)
						{
							//wouldn't like to play new game - return to current one
						}
					}
					else
					{
						//else if a game has been saved
						surrender();
						loadGame(false);
					}

				}
				else if (result == JOptionPane.NO_OPTION)
				{
					// do nothing - let user continue playing game
				}
			}
		}
		else if(source.getText().equals("Surrender"))
		{	
			if(gameOver == true)
			{
				JOptionPane.showConfirmDialog(frame,
						"No game is in progress to surrender.\n" +
						"Please select another option from the menu bar.",
						"ERROR",
						JOptionPane.DEFAULT_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
				int result = JOptionPane.showConfirmDialog(frame,
						"You have chosen to surrender!\n" +
						"This option will count as a loss against you.\n" +
						"Select YES if you would like to surrender.\n" +
						"Select NO if you would like to continue playing.",
						"Surrender!",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);
	
				if (result == JOptionPane.YES_OPTION)
				{
					int result2 = JOptionPane.showConfirmDialog(frame,
							"You have surrendered!\n" +
							"Would you like to play a new game?\n" +
							"Select YES if you would like to play a new game.\n" +
							"Select NO if you would like exit the application.",
							"New Game?",
							JOptionPane.YES_NO_OPTION,
							JOptionPane.WARNING_MESSAGE);
	
					if (result2 == JOptionPane.YES_OPTION)
					{
						//update statistics
						surrender();
						
						newMenu();
					}
					else if (result2 == JOptionPane.NO_OPTION)
					{
						System.exit(0);
					}
				}
				else if (result == JOptionPane.NO_OPTION)
				{
					//do not surrender - continue playing current game
				}
			}
		}
		else if(source.getText().equals("Show Statistics"))
		{
			stats();
		}
		else if(source.getText().equals("Help"))
		{
			helpRules();

		}
		else if(source.getText().equals("Exit"))
		{
			exit();
		}
	}

	private void setUpMenuBar()
	{
		JMenuBar menuBar;
		JMenu menu;

		//Create the menu bar.
		menuBar = new JMenuBar();

		//Build the menu.
		menu = new JMenu("File");
		menuBar.add(menu);
		
		//create and add JMenuItems
		JMenuItem newGame= new JMenuItem("New Game");
		JMenuItem loadGame= new JMenuItem("Load Game");
		JMenuItem surrender= new JMenuItem("Surrender");
		JMenuItem showStats= new JMenuItem("Show Statistics");
		JMenuItem help= new JMenuItem("Help");
		JMenuItem exit= new JMenuItem("Exit");

		newGame.addActionListener(this);
		loadGame.addActionListener(this);
		surrender.addActionListener(this);
		showStats.addActionListener(this);
		help.addActionListener(this);
		exit.addActionListener(this);

		menu.add(newGame);
		menu.add(loadGame);
		menu.add(surrender);
		menu.add(showStats);
		menu.add(help);
		menu.add(exit);

		//add menu to frame
		frame.setJMenuBar(menuBar);
	}

	private void newGame()
	{
		//after initial game play - no longer need to create GUI
		newFromMenuBar = false;
		
		newBoard();
		
		if(board.gameOver() == true)
		{
			gameOver = true;
			
			int result2 = JOptionPane.showConfirmDialog(frame,
					"Your game has ended.\n" +
					"Would you like to play a new game?\n",
					"Game Over",
					JOptionPane.YES_NO_OPTION,
					JOptionPane.WARNING_MESSAGE);

			if (result2 == JOptionPane.YES_OPTION)
			{
				newMenu();
			}
			else if (result2 == JOptionPane.NO_OPTION)
			{
				//do nothing - return to gui
			}
		}
			
				
		//game = new Game(8,8, playAI);
			
	}
	
	/**
	 * Moves the selected piece to the new coordinates and 
	 * deletes it from the original coordinates
	 * 
	 * @param one the original coordinate
	 * @param two the new coordinate
	 */
	public void movePieces(Coordinates one, Coordinates two)
	{
        
        board.placePiece(board.getButton(one.getRow(), one.getColumn()).getIcon(), two.getRow(), two.getColumn());
        board.removePiece(one.getRow(), one.getColumn());
        
        if(!board.getWhoTurn())
        {
        	txtTurn.setText("Player 1's Turn (Black)");
        }
        else if(board.getWhoTurn())
        {
        	txtTurn.setText("Player 2's Turn (Red)");
        }    
        
        if(board.gameOver())
		{
        	
			if(board.blackWin())
			{
				stats.incrementWins();
				//if(stats.)
				//Grab the time it took to complete that game.
				//Compare to the stat fastest time
				//If less, make this the new fastest time.
				
				//POPS UP A WIN SCREEN
				JOptionPane.showConfirmDialog(frame,
						"Congratulations!\n You have won the game!",
						"WINNER!!!",
						JOptionPane.DEFAULT_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
				stats.incrementLoses();
				
				//POPS UP A LOSE SCREEN
				JOptionPane.showConfirmDialog(frame,
						"You Lose.",
						"Game Over.",
						JOptionPane.DEFAULT_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
			}

			newMenu();
		}
	}
	
	/**
	 * Removes a piece 
	 * 
	 * @param remove the coordinates of the piece to be removed
	 */
	public void removePiece(Coordinates remove)
	{
		board.removePiece(remove.getRow(), remove.getColumn());
	}
	
	/**
	 * Kings a piece
	 * 
	 * @param king the coordinates 
	 * @param isBlack the type of king 
	 */
	public void kingPiece(Coordinates king, boolean isBlack)
	{
		ImageIcon blackKing = new ImageIcon("blackKing.gif");
		ImageIcon redKing = new ImageIcon("redKing.gif");
		
		if(isBlack)
		{
			board.placePiece(blackKing, king.getRow(), king.getColumn());
		}
		else if(!isBlack)
		{
			board.placePiece(redKing, king.getRow(), king.getColumn());
		}
	}

	private void loadGame(boolean firstGame)
	{
		startFrame.dispose();
		
		if(newFromMenuBar) {
			setUpGameGUI();
			newFromMenuBar=false;
		}
				
		if (firstGame) {
			newBoard();
		}
		
		board.loadBoard(txtTurn);
	}

	private boolean savedGameExists()
	{
		File savedGameFile = new File("saved_game.txt");
		boolean savedGameExists = savedGameFile.exists();

		if (savedGameExists)
		{
			return true;
		}
		
		return false;
	}

	private void surrender()
	{
		stats.incrementLoses();
	}
	
	public void setTimer(long alreadyElapsedTime) {
		final Date startTime = new Date(); 
		if(timer != null) {
			timer.removeAll();
		}
		timer = new TimerGUI(startTime, alreadyElapsedTime);
		timer.setVisible(true);  
		contentPane.add(timer);
	}
		
	private void stats()
	{
		JFrame newFrame = new JFrame("Game Statistics");

		newFrame.setBounds(100, 100, 223, 153);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0};
		gridBagLayout.rowHeights = new int[]{0};
		gridBagLayout.columnWeights = new double[]{1.0};
		gridBagLayout.rowWeights = new double[]{1.0};
		newFrame.getContentPane().setLayout(gridBagLayout);
		
		JPanel panel_1 = new JPanel();
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.anchor = GridBagConstraints.WEST;
		gbc_panel_1.fill = GridBagConstraints.VERTICAL;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 0;
		newFrame.getContentPane().add(panel_1, gbc_panel_1);

		String statStr = "";
		statStr += "Wins: " + stats.getWins();
		statStr += "\nLoses: " + stats.getLoses();
		statStr += "\nDraws: " + stats.getDraws();
		statStr += "\nFastest time: " + stats.getTime();
		
		JTextArea txtrFastestTime = new JTextArea(statStr);
		txtrFastestTime.setBackground(UIManager.getColor("ColorChooser.background"));
		txtrFastestTime.setColumns(8);
		txtrFastestTime.setRows(6);
		panel_1.add(txtrFastestTime);
		
		newFrame.setVisible(true);
	}

	/** 
	 * Code to implement upon exit of program
	 * Save board etc.
	 */
	private void exit()
	{       
		if(gameOver == true)
		{
			int result2 = JOptionPane.showConfirmDialog(frame,
					"You have selected to exit the application.\n" +
					"Would you really like to exit?\n",
					"Exit Application",
					JOptionPane.YES_NO_OPTION,
					JOptionPane.WARNING_MESSAGE);

			if (result2 == JOptionPane.YES_OPTION)
			{
				System.exit(0);
			}
			else if (result2 == JOptionPane.NO_OPTION)
			{
				//do nothing - return to gui
			}
		}
		//else if try to exit during a running game
		else
		{
			int result = JOptionPane.showConfirmDialog(frame,
					"You have selected to exit the application.\n" +
					"Exiting before the end of a game counts as surrendering and\n" +
					"will be counted as a loss unless you save your current game!\n\n" +
					"Select YES if you would like to save your current game before exiting.\n" +
					"Select NO if you would like to exit without saving your game.\n" +
					"Select CANCEL if you would like to continue playing.",
					"Exit Application",
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.WARNING_MESSAGE);
	
			if (result == JOptionPane.YES_OPTION)
			{
				//save statistics & board config. then exit
				surrender();
				board.saveBoard();
				
				System.exit(0);
			}
			else if(result == JOptionPane.NO_OPTION)
			{
				//update statistics - player lost
				surrender();
				
				System.exit(0);
	
			}
			else if(result == JOptionPane.CANCEL_OPTION)
			{
				//do nothing - resume game
			}
		}
	}
	
	/**
	 * 
	 * Return the rules of checkers 
	 */
	private void helpRules()
	{
		String s = "";

		s += "A piece may only move one square per turn unless it performs a jump over an adjacent opposing piece\n" +
		"A jump is made by skipping over an adjacent opposing piece. Single jumps can only be made in a\n" +
		"straight line. A piece that performs a jump must move again if the next move is also a jump.\n" +
		"Once a piece is jumped, it is removed from the board. When a player's piece reaches the far \n" +
		"end of the board (the opponent's king row) that piece is crowned and becomes a king. A king must\n" +
		"still move on the dark squares, but can move forward and backward. The game ends when one player\n" +
		"cannot make any more moves. This can happen by losing all pieces or by being blocked from further movement.";

		JFrame newFrame = new JFrame("The Rules Of Checkers");
		newFrame.pack();
		newFrame.setVisible(true);
		newFrame.setBounds(10, 10, 650, 150);
		
		JTextArea helpTxt = new JTextArea(s);
		helpTxt.setBackground(UIManager.getColor("ColorChooser.background"));
		newFrame.add(helpTxt);
	}

	private void helpMenu()
	{
		String s = "";

		s += "Checkers Options Help Menu\n\n"
			+"New Game\n"
			+"	To start a new game. You will be given the option to play the game\n"
			+"	against another player, or against the computer AI.\n"
			+"Load Game\n"
			+"	To load a game that you have previously saved upon exiting. If no\n"
			+"	game configuration has been saved, this option is not available.\n"
			+"Statistics\n"
			+"	To display statistics from previously played games. Statistics include\n"
			+"	number of wins vs. losses.\n"
			+"Help\n"
			+"	Displays this menu.\n"
			+"Exit\n"
			+"	To exit the application.\n";

		JFrame newFrame = new JFrame("Help Menu");
		newFrame.pack();
		newFrame.setVisible(true);
		newFrame.setBounds(10, 10, 480, 300);

		JTextArea helpTxt = new JTextArea(s);
		helpTxt.setBackground(UIManager.getColor("ColorChooser.background"));
		newFrame.add(helpTxt);
	}

	//private inner class
	private class ImagePanel extends JPanel{

		private BufferedImage image;

		public ImagePanel() {
			try {                
				image = ImageIO.read(new File("octopus.jpg"));
			} catch (IOException ex) {
				// handle exception...
			}
		}

		@Override
		public void paintComponent(Graphics g) {
			g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters

		}

	}

	// private inner class to make timer
	private class TimerGUI extends JPanel  
	{  

		public TimerGUI(final Date startTime, final long alreadyElapsedTime)  
		{  

			final JLabel timeLabel = new JLabel();  
			add(timeLabel);

			ActionListener timerListener = new ActionListener()  
			{  
				public void actionPerformed(ActionEvent e)  
				{
					Date currentTime = new Date();
					long secElapsedDiff = (currentTime.getTime() - startTime.getTime() 
							+ alreadyElapsedTime)/1000;
					elapsedTimeSec = secElapsedDiff;
					long secElapsed = 0;
					long minElapsed = 0;
					long hourElapsed = 0;
					
					secElapsed = secElapsedDiff % 60;
					minElapsed = secElapsedDiff / 60;
					hourElapsed = secElapsedDiff / 1440;
									
					String timeElapsed = String.format("%02d", hourElapsed) + ":" 
							+ String.format("%02d", minElapsed) + ":"+ String.format("%02d", secElapsed);
					timeLabel.setText(timeElapsed);  
				}  
			};
			Timer timer = new Timer(1000, timerListener);  
			// to make sure it doesn't wait one second at the start  
			timer.setInitialDelay(0);  
			timer.start();  
		}
	} 
	
	public long elapsedTimeInSec() {
		return elapsedTimeSec;
	}
}